<template>
  <div>
    <n-space vertical size="large">
      <n-card title="欢迎使用志愿者服务管理系统">
        <n-text>您好，{{ userStore.nickname }}！</n-text>
        <n-text depth="3">
          {{ userStore.isAdmin() ? '管理员' : '志愿者' }}
        </n-text>
      </n-card>

      <n-grid :cols="4" :x-gap="16" :y-gap="16" responsive="screen">
        <n-gi>
          <n-card hoverable>
            <n-statistic label="我的积分" :value="statistics.totalPoints || 0">
              <template #prefix>
                <n-icon size="24" color="#18A058">
                  <TrophyOutline />
                </n-icon>
              </template>
            </n-statistic>
          </n-card>
        </n-gi>

        <n-gi>
          <n-card hoverable>
            <n-statistic label="参与活动" :value="statistics.activityCount || 0">
              <template #prefix>
                <n-icon size="24" color="#2080f0">
                  <CalendarOutline />
                </n-icon>
              </template>
            </n-statistic>
          </n-card>
        </n-gi>

        <n-gi>
          <n-card hoverable>
            <n-statistic label="服务时长" :value="formatHours(statistics.totalHours)" suffix="小时">
              <template #prefix>
                <n-icon size="24" color="#f0a020">
                  <TimeOutline />
                </n-icon>
              </template>
            </n-statistic>
          </n-card>
        </n-gi>

        <n-gi>
          <n-card hoverable>
            <n-statistic label="完成需求" :value="statistics.demandCount || 0">
              <template #prefix>
                <n-icon size="24" color="#d03050">
                  <CheckmarkCircleOutline />
                </n-icon>
              </template>
            </n-statistic>
          </n-card>
        </n-gi>
      </n-grid>

      <n-card title="快速入口">
        <n-space>
          <n-button type="primary" @click="router.push('/activity/list')">
            <template #icon>
              <n-icon><CalendarOutline /></n-icon>
            </template>
            浏览活动
          </n-button>
          <n-button type="info" @click="router.push('/demand/list')">
            <template #icon>
              <n-icon><ListOutline /></n-icon>
            </template>
            查看需求
          </n-button>
          <n-button type="success" @click="router.push('/point')">
            <template #icon>
              <n-icon><TrophyOutline /></n-icon>
            </template>
            我的积分
          </n-button>
          <n-button type="warning" @click="router.push('/volunteer/my-info')">
            <template #icon>
              <n-icon><PersonOutline /></n-icon>
            </template>
            完善资料
          </n-button>
        </n-space>
      </n-card>

      <n-card title="最新通知">
        <n-list hoverable clickable>
          <n-list-item v-for="item in notifications" :key="item.id" @click="router.push('/notification/list')">
            <n-thing :title="item.title">
              <template #description>
                <n-text depth="3">{{ formatDate(item.createTime) }}</n-text>
              </template>
              {{ item.content.substring(0, 100) }}...
            </n-thing>
          </n-list-item>
        </n-list>
        
        <n-empty v-if="!notifications.length" description="暂无通知" />
      </n-card>
    </n-space>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getNotificationList } from '@/api/notification'
import { getUserStatistics } from '@/api/statistics'
import { CalendarOutline, ListOutline, TrophyOutline, PersonOutline, TimeOutline, CheckmarkCircleOutline } from '@vicons/ionicons5'

const router = useRouter()
const userStore = useUserStore()

const statistics = ref({
  totalPoints: 0,
  activityCount: 0,
  totalHours: 0,
  demandCount: 0
})
const notifications = ref([])

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN')
}

const formatHours = (hours) => {
  if (!hours || hours === 0) return 0
  return typeof hours === 'number' ? Number(hours.toFixed(1)) : Number(hours)
}

const loadData = async () => {
  try {
    // 加载通知
    const notifRes = await getNotificationList({ page: 1, size: 5 })
    notifications.value = notifRes.data.records || []

    // 加载用户统计数据（从新的统计API）
    if (!userStore.isAdmin()) {
      const statsRes = await getUserStatistics(userStore.userId)
      console.log('用户统计数据:', statsRes.data)
      if (statsRes.data) {
        statistics.value.totalPoints = statsRes.data.totalPoints || 0
        statistics.value.totalHours = statsRes.data.totalHours || 0
        statistics.value.activityCount = statsRes.data.participatedActivities || 0
        statistics.value.demandCount = statsRes.data.completedDemands || 0
        console.log('更新后的统计数据:', statistics.value)
      }
    }
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

onMounted(() => {
  loadData()
})
</script>

